package servlet;
import dao.BlogDao;
import enity.*;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper=new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BlogDao blogDao=new BlogDao();
        String respJson="";
        String  UserId=req.getParameter("userId");
        String blogId=req.getParameter("blogId");
        System.out.println("blogId"+blogId);
        if(blogId==null){
            List<Blog>blogs=blogDao.getBlogs();
            respJson=objectMapper.writeValueAsString(blogs);
        }else{
            Blog blog=blogDao.getBlog(Integer.parseInt(blogId));
            respJson=objectMapper.writeValueAsString(blog);
        }
        System.out.println("respJson:"+respJson);
        resp.setContentType("application/json; charset=utf8");
        System.out.println("++++++++++++++:"+UserId);
        resp.getWriter().write(respJson);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String title=req.getParameter("title");
        String content=req.getParameter("content");
        if(title==null||title.length()==0||content==null||content.length()==0){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前传来的标题或正文为空！无法新增博客");
            return;
        }
        HttpSession session=req.getSession(false);
        if(session==null){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前用户未登录");
            return;
        }
        User user=(User)session.getAttribute("user");
        if(user==null){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前用户未登录");
            return;
        }
        Blog blog=new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        BlogDao blogDao=new BlogDao();
        blogDao.insert(blog);
        resp.sendRedirect("blog_list.jsp");
    }
}
